package com.study.demoservice.controller;

import com.study.demoservice.bean.Student;
import com.study.demoservice.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Value 注解测试 Demo
 */
@RestController
public class ValueController {

    /**
     * username 的值不是配置文件中的值是因为 在系统环境变量中有同名的配置
     */
    @Value("${username}")
    private String username;

    @Value("${password}")
    private String password;

    /**
     * 通过 @Value 的方式注入 Bean，#{} 中是 bean 的 id
     * @see ValueController#getStudent()
     *
     */
    @Value("#{student2}")
    private Student student;

    @Autowired
    private ServiceImpl service;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 测试配置文件中 username 和 password 的值
     *
     * @return
     */
    @RequestMapping(path = "user", method = RequestMethod.GET)
    public String getUser(){
        return username + ":" + password;
    }

    /**
     * 测试 {@link ValueController#student} 中的 @Value 注解能否成功注入
     *
     * @return
     */
    @RequestMapping(path = "student", method = RequestMethod.GET)
    public Student getStudent(){
        return student;
    }

    /**
     * 通过这种方式获取，获取的是同一个，多例并没有生效
     *
     * @return
     */
    @RequestMapping(path = "getServiceHash", method = RequestMethod.GET)
    public String getServiceHash(){
        return service.toString();
    }

    /**
     * 每次都获取新的
     *
     * @return
     */
    @RequestMapping(path = "getServiceHash2", method = RequestMethod.GET)
    public String getServiceHash2(){
        return applicationContext.getBean(ServiceImpl.class).toString();
    }

    /**
     * 每次都获取新的
     *
     * @return
     */
    @RequestMapping(path = "getServiceHash3", method = RequestMethod.GET)
    public String getServiceHash3(){
        return getServiceImpl().toString();
    }

    /**
     * 是通过 cglib 代理，返回什么不重要，所以很多时候可以放在抽象方法
     * @return
     */
    @Lookup
    public ServiceImpl getServiceImpl() {
        return null;
    };

}
